<template>
  <div class="Ota">
    <div class="page-head">
      <div class="page-title">OTA管理</div>
      <div class="page-tool">
        <el-select
          v-model="cnc"
          placeholder="CNC类型筛选"
          class="tool-sel"
          clearable
          @change="getList"
        >
          <el-option
            v-for="item in cncSel"
            :key="item.k"
            :label="item.v"
            :value="item.k">
          </el-option>
        </el-select>
        <el-select
          v-model="purpose"
          placeholder="用途筛选"
          class="tool-sel"
          clearable
          @change="getList"
        >
          <el-option
            v-for="item in purposeSel"
            :key="item.k"
            :label="item.v"
            :value="item.k">
          </el-option>
        </el-select>
        <div
          class="tool-btn"
          @click="open('add')"
        >
          上传文件
        </div>
      </div>
    </div>
    <div class="page-body">
      <div class="table_data">
        <el-table :data="tableData" stripe border :fit="true" :height="$tableHeight">
          <el-table-column
            prop="version"
            label="版本号"
          >
          </el-table-column>
            <el-table-column
            prop="name"
            label="文件名称"
          >
          </el-table-column>
          <el-table-column
            prop="cnc"
            label="CNC类型"
          >
            <template slot-scope="{ row }">
              <div>
                {{cncSel.find(s => s.k == row.cnc).v}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="用途"
            prop="purpose"
          >
            <template slot-scope="{ row }">
              <div>
                {{purposeSel.find(s => s.k == row.purpose).v}}
              </div>
            </template>
          </el-table-column>
          

          <el-table-column
            prop="time"
            label="版本上传时间"
          >
            <template slot-scope="{ row }">
              <div>
                {{format(row.time, 'YYYY-MM-DD')}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :show-overflow-tooltip="true"
            label="备注"
            prop="remark"
          >
          </el-table-column>
          
          <el-table-column label="操作" align="center" width="100">
            <template slot-scope="{ row }">
              <div class="operation-col">
                <div
                  class="txt-btn"
                  @click="toNext(row)"
                >
                  <el-tooltip effect="dark" content="更新设备" placement="top-start">
                    <img src="~assets/img/group.png" alt="">
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <pagina-tion
          class="page-pager"
          v-show="total >= 0"
          :background="true"
          :total="total"
          :offset.sync="offset"
          :limit.sync="limit"
          @pagination="getChangePage"
          @sizeChange="getSizePage"
        />
      </div>
    </div>

    <!-- 新增和修改弹框 -->
    <el-dialog
      :visible.sync="model.visible"
      width="370px"
      title="上传更新文件"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialog-body">
        <el-form
          ref="form"
          :model="form"
          label-width="110px"
          label-position="left"
        >
          <el-form-item label="版本文件" class="upload-form-item required">
            <el-input
              :readonly="true"
              placeholder="请选择要上传的文件"
              v-model="fileName"
              name="programUrl"
              v-validate="'required'"
            />
            <input
              type="file"
              class="file-input"
              ref="fileInput"
              @change="fileChange($event)"
            >
            <img src="~assets/img/pick.png" class="pick-img">
            <div v-show="errors.has('programUrl')" class="el-form-item__error">{{ errors.first('programUrl') }}</div>
          </el-form-item>
          <el-form-item label="版本号" class="required">
            <el-input
              name="version"
              placeholder="请输入版本号"
              v-model="form.version"
              v-validate="'required'"
            />
            <div v-show="errors.has('version')" class="el-form-item__error">
              {{ errors.first("version") }}
            </div>
          </el-form-item>
          
          <el-form-item label="CNC类型" label-position="left" class="required">
            <el-select
              v-model="form.cnc"
              name="cnc_name"
              placeholder="请选择CNC类型"
              v-validate="'required'"
            >
              <el-option
                v-for="item in cncSel"
                :key="item.k"
                :label="item.v"
                :value="item.k">
              </el-option>
            </el-select>
            <div
              v-show="errors.has('cnc_name')"
              class="el-form-item__error"
            >
              {{ errors.first("cnc_name") }}
            </div>
          </el-form-item>
          <el-form-item label="用途" label-position="left" class="required">
            <el-select
              v-model="form.purpose"
              name="purpose"
              placeholder="请选择用途"
              v-validate="'required'"
            >
              <el-option
                v-for="item in purposeSel"
                :key="item.k"
                :label="item.v"
                :value="item.k">
              </el-option>
            </el-select>
            <div
              v-show="errors.has('purpose')"
              class="el-form-item__error"
            >
              {{ errors.first("purpose") }}
            </div>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" maxlength="128" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Loading } from 'element-ui'
import { format } from "silly-datetime";
import * as api from "@/api";
import { limit, smallLimit } from "@/consts/consts";
import { otaKey } from "@/consts/formKey";
import paginaTion from "@/components/libs/paginaTion";

export default {
   components:{
    paginaTion
  },
  data() {
    return {
      limit,
      total: 0,
      offset: 0,
      tableData: [],
      cncSel: [],
      cnc: '',
      purposeSel: [],
      purpose: '',
      format,
      search: "",
      model: {
        type: "add",
        visible: false,
      },
      id: '',
      form: {
        ...otaKey
      },
      
      visibility: false,
      detailVisable: false,
      fileName: '',
      fileSize: '',
      loading: null,
    }
  },


  methods: {
    open(type, row = null) {
      this.$validator.reset();
      this.model.type = type;
      if (row) {
        for (const k in otaKey) {
          this.form[k] = row[k];
        }
        this.id = row.version_id;
      }

      this.model.visible = true;
    },

    openDetail(row) {
      this.detail = row;
      this.detailVisable = true;
    },

    closeDetail() {
      this.detail = {};
      this.detailVisable = false;
    },

    getChangePage(val) {
      sessionStorage.setItem('otaCurPage', val.offset)
      this.offset = val.offset;
      this.getList();
    },
    
    getSizePage(val) {
      this.offset = 0
      this.getList();
    },

    close() {
      this.model.visible = false;
      this.form = { ...otaKey };
      this.fileName = '';
      this.$refs.fileInput.value = ''
    },

    submit() {
      this.$validator.validateAll().then((valid) => {
        if (valid) {
          this.addOrEdit();
        } else {
          this.$message.warning("有信息未填写正确");
        }
      });
    },

    toNext(row) {
      this.$router.push({
        name: 'otaUpdate',
        query: {
          version_id: row.version_id
        }
      })
    },
    
    fileChange(e) {
      let file = this.$refs.fileInput.files[0];
      let index = file.name.lastIndexOf(".")
      let suf = file.name.substr(index+1)
      console.log('后缀名是： ', suf)
      this.fileSize = file.size
      this.loading = Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.fileName = file.name
      this.upload(file)
      
      
    },
        
    async upload(file) {
      console.log('ff: ', file)
      let [n, suf] = file.name.split('.')
      let fileName = `${n}_${+new Date}.${suf}`

      let { code, data } = await api.upload(this).upload(file)
      if (code === 0) {
        this.form.url = data.url
        this.form.name = file.name
        this.fileName = file.name
        this.loading.close()
      }
    },
        
    // 下拉列表
    async downList(type) {
      const { code, data } = await api.dropdown(this).downList({
        type
      })
      if (code === 0) {
        this[`${type}Sel`] = data
      }
    },

    // 机构列表
    async getList() {
      const { code, data, total } = await api.ota(this).getList({
        offset: this.offset,
        limit: this.limit,
        cnc: this.cnc,
        purpose: this.purpose
      });
      if (code === 0) {
        this.tableData = data
        this.total = total
      }
    },


    async addOrEdit() {
      let fn = this.model.type === "add" ? "add" : "update";
      const { code } = await api.ota(this)[fn](this.form, this.id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.close();
        this.getList();
      }
    },

    async init() {
      await this.downList('cnc')
      await this.downList('purpose')
      this.getList()
    }
  },
  created() {
    let curPage = sessionStorage.getItem('otaCurPage')
    this.offset = +curPage
    this.init()
  },
};
</script>

<style lang="stylus">
.Ota {

}

</style>